package com.shengwei.truck.driver.view.ui.settings;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;
import androidx.lifecycle.Observer;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.AppInfo;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.databinding.ActivitySettingsBinding;
import com.shengwei.truck.driver.utils.CommonUtil;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.utils.NotificationUtils;
import com.shengwei.truck.driver.utils.UpdateApp;
import com.shengwei.truck.driver.view.ui.ActivityCollectorUtil;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.view.ui.app.WebViewBrowser;
import com.shengwei.truck.driver.view.ui.mine.userinfo.LoginActivity;
import com.shengwei.truck.driver.vm.LoginViewModel;

import java.lang.ref.WeakReference;

/**
 * 设置页面
 */
public class SettingsActivity extends BaseActivity<LoginViewModel, ActivitySettingsBinding> implements View.OnClickListener {
    //检查更新
    private NotificationManager mNotificationManager;
    private Notification mNotification;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        checkUpdate(UpdateApp.CHECK_ONLY); //只检查更新，用于显示隐藏小红点
        initLiveDataObersve();
    }
    /**
     * 初始化控件
     */
    private void initView() {
        mDataBinding.modifyPwdLayout.setOnClickListener(this);
        mDataBinding.userAgreeLayout.setOnClickListener(this);
        mDataBinding.userPrivacyLayout.setOnClickListener(this);
        mDataBinding.btExitLogin.setOnClickListener(this);
        mDataBinding.updateAppLayout.setOnClickListener(this);
        //检查更新相关
        String versionName = UpdateApp.getVersionName(this);
        mDataBinding.tvVersionName.setText(versionName);
       //gxw-要恢复 initNotifyBarUpdate();
    }

    /**
     * 接口调用成功时，监听接口返回的数据
     */
    private void initLiveDataObersve() {
        //监听 "退出登录"接口返回的数据
        mViewModel.getLogoutLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        User user = User.getInstance(getApplicationContext());
                        user.setToken("");
                        user.setHeadImvUrl("");
                        Intent i = new Intent(SettingsActivity.this, LoginActivity.class);
                        startActivity(i);
                    }
                });
            }
        });
    }


    @Override
    public int getContentViewId() {
        return R.layout.activity_settings;
    }


    //检查更新START
    /**
     * 初始化通知栏上的APP升级进度条
     */
    public void initNotifyBarUpdate() {
        mNotification = buildNotification();
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        //mNotificationManager.notify(101,mNotification);
    }


    /**
     * 构建Notification，以保证后台连续定位
     * @return
     */
    public Notification buildNotification() {
        Notification notification;
        String notifyTitle = this.getResources().getString(R.string.notify_title);
        String notifyContent = this.getResources().getString(R.string.notify_content);
        NotificationUtils mNotificationUtils;
        //设置后台定位
        if (Build.VERSION.SDK_INT >= 26) {  //AndroidO及以上系统
            mNotificationUtils = new NotificationUtils(this);
            Notification.Builder builder2 = mNotificationUtils.getAndroidChannelNotification(notifyTitle, notifyContent);
            builder2.setOnlyAlertOnce(true);
            builder2.setOngoing(true);
            builder2.setTicker("来回好运");
            builder2.setSound(null);
            builder2.setVibrate(null);
            builder2.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);//取消震动,铃声其他都不好使
            notification = builder2.build();

        } else {
            mNotificationUtils = new NotificationUtils(this,true);
            Notification.Builder builder = mNotificationUtils.getAndroidNotification (notifyTitle, notifyContent);
            notification = builder.build(); // 获取构建好的Notification
        }
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        notification.contentView = new RemoteViews(this.getPackageName(), R.layout.update_notify);
        return notification;
    }

    /**
     * 监控安装包下载进度
     */

    public class MyDownLoadListener implements UpdateApp.DownLoadListener {

        @Override
        public void onSuccess() {
            //更新通知栏进度条
            if(mNotificationManager != null){
                mNotification.contentView.setTextViewText(R.id.content_view_text1, "下载完成！");
                mNotification.contentView.setProgressBar(R.id.content_view_progress, 100, 100, false);
                mNotificationManager.cancel(101);
            }
            MyApplication.UPDATE_STATE = 0; //未正在更新
        }

        @Override
        public void onFailed() {
            if(mNotificationManager != null) {
                mNotificationManager.cancel(101);
            }
            MyApplication.UPDATE_STATE = 0; //未正在更新
            Toast.makeText(SettingsActivity.this,"下载失败",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onProgress(int progress) {
            if(mNotificationManager != null){
                mNotification.contentView.setTextViewText(R.id.content_view_text1, "正在下载...  "+progress+"%");
                mNotification.contentView.setProgressBar(R.id.content_view_progress, 100, progress, false);
                mNotificationManager.notify(101, mNotification);
            }
        }
    }

    /**
     * 检查新版本
     * @param checkType 0只检查新版本, 如果有则显示小红点;
     *                  1 点击“检查新版本”并弹出升级提示框
     */
    private void checkUpdate(final int checkType) {

        final UpdateApp updateApp = new UpdateApp(this);
        updateApp.checkUpdate(checkType, new UpdateApp.GetAppInfoListener() {
            @Override
            public void onSuccess(AppInfo appInfo, int checkType) {

                if(checkType == 1)  //点击升级
                {
                    if(appInfo.getHaveNewVersion() == 1)  //如果有新版本，则去下载
                    {
                        String downloadUrl = appInfo.getDownloadUrl();
                        String updateContent = appInfo.getUpContent();
                        updateApp.downLoad(downloadUrl,updateContent,new MyDownLoadListener());
                    }
                    else {
                        Toast.makeText(SettingsActivity.this,"已经是最新版本了",Toast.LENGTH_SHORT).show();
                    }
                }
                else {   //只检查更新
                    if(appInfo.getHaveNewVersion() == 1)
                        mDataBinding.imvUpdateTip.setVisibility(View.VISIBLE);
                }
            }
            @Override
            public void onFailed(String errMsg) {
                String tip;

                if(!TextUtils.isEmpty(errMsg) && !(errMsg.contains("未检查到"))) {
                    tip = errMsg;
                }
                else
                {
                    tip = "已经是最新版本了";
                }

                if(checkType == 1)
                    Toast.makeText(SettingsActivity.this,tip,Toast.LENGTH_SHORT).show();

            }
        });
    }


    //检查更新END
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.updateAppLayout:  //检查更新
                checkUpdate(UpdateApp.CHECK_AND_DOWNLOAD);
              //  String hasNew = this.getResources().getString(R.string.has_newest);
              //  MyToast.showToastCenter(new WeakReference<>(SettingsActivity.this),hasNew,Toast.LENGTH_SHORT,true);
                break;
            case R.id.modifyPwdLayout:
                goSettingsActivity();
                break;
            case R.id.userAgreeLayout:
                String userAgree = this.getResources().getString(R.string.user_agree_settings);
               //gxw- 要恢复gotoWebviewBrowser(MyConstant.WEB_TEST,userAgree);
                break;
            case R.id.userPrivacyLayout:
                 String userPrivacy = this.getResources().getString(R.string.user_privacy_settings);
                 gotoWebviewBrowser(MyConstant.WEB_PRIVACY,userPrivacy);
                break;
            case R.id.btExitLogin:
                ActivityCollectorUtil.finishAllActivity();
                mViewModel.logout();
                break;
        }

    }

    /**
     * 去修改密码页面
     */
    public void goSettingsActivity() {
        String mobile = "18392086025";
        boolean isMobile = CommonUtil.checkMobile(mobile, new WeakReference<>(this),false);
        Intent intent = new Intent(this.getApplicationContext(), ModifyPwdActivity.class);
        intent.putExtra("fromPage", MyConstant.MODIFY_PASSWORD); //忘记密码
        //如果是手机号，则直接传递到“忘记密码”页面去，用于获取短信码
        if(isMobile) {
            intent.putExtra("mobileNum", mobile); //忘记密码
        }
        startActivity(intent);
    }


    /**
     * 跳转到浏览器网页显示使用说明等文章
     * @param url
     * @param pageTitle
     */
    public void gotoWebviewBrowser(String url,String pageTitle)
    {
        Intent goReadMe = new Intent(SettingsActivity.this, WebViewBrowser.class);
        goReadMe.putExtra("url",url);
        goReadMe.putExtra("title",pageTitle);
        startActivity(goReadMe);
    }
}